package it.xiuxian.dagongyuzhou

import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Process
import androidx.databinding.library.BuildConfig
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.launcher.ARouter
import com.bytedance.applog.AppLog
import com.bytedance.applog.InitConfig
import com.bytedance.applog.util.UriConstants
import com.bytedance.sdk.openadsdk.TTAdConfig
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTAdSdk.InitCallback
import com.tencent.bugly.crashreport.CrashReport
import it.xiuxian.lib.utils.MediaServiceImpl
import it.xiuxian.lib.base.App
import it.xiuxian.lib.service.CommonService

class BaseApplication: Application() {
    @JvmField
    @Autowired
    var commonService: CommonService? = null
    override fun onCreate() {
        super.onCreate()
        var callback = BaseActivityLifecycleCallbacks()
        App.INSTANCE.registerActivityLifecycleCallbacks(callback)
        //OSETSDK.getInstance().init(this, "4C9E8FBD4A619AAE")
        if(BuildConfig.DEBUG){
            ARouter.openLog()
            ARouter.openDebug()
        }else{
            Thread.setDefaultUncaughtExceptionHandler { t: Thread?, e: Throwable? ->
            }
        }
        ARouter.init(this)
        ARouter.getInstance().inject(this)
        commonService!!.initOkGoHttp(this, true)
        CrashReport.initCrashReport(getApplicationContext(), "3ca7f76cc5", false);
        initAPPLog()
        initADSDK()
        //TTAdManagerHolder.init(this)


    }
    private var sInit = false
    private fun initADSDK() {
        if (!sInit) {
            //TTAdSdk.init(context, buildConfig(context));
            TTAdSdk.init(this, TTAdConfig.Builder()
                .appId("5255152")
                .useTextureView(true) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView
                .allowShowNotify(true) //是否允许sdk展示通知栏提示
                .debug(true) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
                .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI, TTAdConstant.NETWORK_STATE_3G) //允许直接下载的网络状态集合
                .supportMultiProcess(true) //是否支持多进程，此处必须为true
                .needClearTaskReset()
                .build(), object : InitCallback {
                override fun success() {
                    if (applicationContext.packageName == getCurrentProcessName()) {
                        //dp
                        initDP()
                    }
                  //  Log.i(TTAdManagerHolder.TAG, "success: " + TTAdSdk.isInitSuccess())
                }

                override fun fail(code: Int, msg: String) {
                  //  Log.i(TTAdManagerHolder.TAG, "fail:  code = $code msg = $msg")
                }
            })
            sInit = true
        }
    }

    private fun initAPPLog() {
        val config = InitConfig(
            "315768",
            "my_channel"
        ) // appid和渠道，appid如不清楚请联系客户成功经理，注意第二个参数 channel 不能为空


        config.setUriConfig(UriConstants.DEFAULT) //上报地址

// 加密开关，SDK 5.5.1 及以上版本支持，false 为关闭加密，上线前建议设置为 true
// 加密开关，SDK 5.5.1 及以上版本支持，false 为关闭加密，上线前建议设置为 true
        AppLog.setEncryptAndCompress(true)

        config.setAutoStart(true)
        AppLog.init(this, config)
    }
    /**
     * 初始化流媒体(小视频、直播)sdk，若未接入流媒体，请忽略
     */
    private fun initDP() {
        //1. 初始化，最好放到application.onCreate()执行
//2. 【重要】如果needInitAppLog=false，请确保AppLog初始化一定要在内容合作sdk初始化前
    /*    val configBuilder = DPSdkConfig.Builder()
            .debug(true)
            .needInitAppLog(false)
            .initListener { isSuccess ->
            //注意：1如果您的初始化没有放到application，请确保使用时初始化已经成功
                //     2如果您的初始化在application
                //isSuccess=true表示初始化成功
                //初始化失败，可以再次调用初始化接口（建议最多不要超过3次)
                isDPInited = isSuccess
               *//* if(!isSuccess){
                    DPSdk.init(this, "SDK_Setting_5255152.json", configBuilder.build())
                }*//*
                Log.e("APP", "init result=$isSuccess")
            }
        DPSdk.init(this, "SDK_Setting_5255152.json", configBuilder.build())*/
        MediaServiceImpl.Companion.instance.init(this)
    }
    private fun getCurrentProcessName(): String{
        val pid = Process.myPid()
        var processName = ""
        val manager =
            applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (process in manager.runningAppProcesses) {
            if (process.pid == pid) {
                processName = process.processName
            }
        }
        return processName
    }
}